package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.Service.MemberService;
import com.itheima.Service.ReportService;
import com.itheima.Service.SetmealService;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.DateUtils;
import freemarker.template.SimpleDate;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;


    //会员数量折线图数据
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        //计算过去一年的12个月
        Map<String, Object> map = new HashMap<>();
        ArrayList<String> months = new ArrayList<>();


        Calendar calendar =Calendar.getInstance();//获得日历对象，模拟时间就是当前时间

        calendar.add(Calendar.MONTH,-12);//计算过去一年过去12个月
        for (int i = 0; i <12 ; i++) {
            calendar.add(Calendar.MONTH,1);//获取calendar指向时间向后推一个月
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(time));
        }
        map.put("months",months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }


    //套餐预约占比饼形图
    @RequestMapping("getSetmealReport")
    public Result getSetmealReport(){
        try {
            Map<String, Object> date = new HashMap();



            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();//setmealCount：每个套餐预约数量组

            List<String> setmealNames = new ArrayList<>();   //setmealNames:套餐名称组

            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            date.put("setmealCount", setmealCount);
            date.put("setmealNames", setmealNames);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, date);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营数据统计
    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> date = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,date);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据
    @RequestMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");//日期
            Integer todayNewMember = (Integer) result.get("todayNewMember");//今日新增会员
            Integer totalMember = (Integer) result.get("totalMember");//总会员
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//本周新增会员
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//本月新增会员
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//今日预约量
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//今日到诊数量
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//本周预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//本周到诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//本月预约数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");//本月到诊数
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");//热门套餐

            //动态获取report_template.xlsx文件绝对路径
            String filePath =request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            //根据提供的Excel模板文件在内存里创建一个Excel对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));


            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);


            //获得第三行
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);//第六个单元格
            cell.setCellValue(reportDate);//写入日期

            //获得第五行
            row = sheet.getRow(4);
            cell=row.getCell(5);
            cell.setCellValue(todayNewMember);//新增会员数（本日）

            cell=row.getCell(7);
            cell.setCellValue(totalMember);//总会员


            //获得第五行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员

            //获取第八行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            //获取第九行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            //获取第十行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            //第13行
            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");//套餐姓名
                Long setmeal_count = (Long) map.get("setmeal_count");//预约数量
                BigDecimal proportion = (BigDecimal) map.get("proportion");//占比
                //获取第十三行
                row = sheet.getRow(rowNum ++);
                //放入数据
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流下载表格,基于浏览器客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //一周内体检收入统计
    @RequestMapping("getSetmealReportMoney")
    public Result getSetmealReportMoney(){
        try {
            //使用工具类找到当前时间前一周内每天的时间日期
            ArrayList<String> dayList = DateUtils.findDaysToWeek();

            List<String> names = setmealService.findSetmealNameCount();   //套餐名称组

            Map<String, Object> date = setmealMoneyToDate(names, dayList);


            return new Result(true, "体检收入统计查询成功", date);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, "体检收入统计查询失败");
        }
    }

    //给定时间内体检收入统计
    @RequestMapping("/getSetmealReportMoneyDate")
    public Result findOrderDate(String value1){
        try {
            String[] split = value1.split(",");
            //拿到每天的日期
            ArrayList<String> dayList = DateUtils.findDaysStr(split[0], split[1]);

            //取出开始和结束时间
            Date sd = DateUtils.parseString2Date(split[0]);
            Date ed = DateUtils.parseString2Date(split[1]);
            //获取当天时间
            Date today = new Date();
            if (sd.getTime()>today.getTime() || ed.getTime()>today.getTime()){
                String over = "timeTOtoday";
                return new Result(false,"未来不可预测哦");
            }

            List<String> names = setmealService.findSetmealNameCount();   //套餐名称组

            Map<String, Object> date = setmealMoneyToDate(names, dayList);

            return new Result(true, "体检收入统计查询成功", date);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, "体检收入统计查询失败");
        }
    }



    /**
     * 获取套餐在区域时间内的金额
     * @param names 所有套餐名
     * @param dayList 区域时间
     * @return 对应套餐在区域时间内的总金额
     */
    public Map<String, Object>  setmealMoneyToDate(List<String> names,  ArrayList<String> dayList){
        Map<String, Object> date = new HashMap();

        List<Map<String, Object>> moneys = new ArrayList<>();

        double sum = 0.0;
        //找到每个套餐名
        for (String name : names) {
            //找到每个套餐的id
            Integer id = setmealService.findnameById(name);

            //当前套餐的金额
            Integer money = setmealService.findSetmealMoney(id);


            //查到当前套餐在时间内的数量
            Double num = setmealService.findSetmealNum(id, dayList);

            Map<String, Object> map = new HashMap<>();

            //当前套餐在时间内的金额
            double znum = money * num;

            sum+=znum;

            map.put("name", name);
            map.put("value", znum);
            moneys.add(map);
        }

        Map<String, Object> map = new HashMap<>();


        //最后将总收入放到集合中
        names.add("总收入");
        map.put("name","总收入");
        map.put("value", sum);
        moneys.add(map);

        date.put("moneys", moneys);
        date.put("names", names);
        return date;
    }
}
